module ApplicationHelper


	def count_unread_notification
		# if current_user.present?
		# 	@count=current_user.notifications.where(unread: true).count
		# else
			@count=0
		# end

	end

	def admin?(user)
		user||=current_user
		user.role?('admin')
	end

	def gravatar_for(user,options={size: 100})
		#1根据用户邮箱显示gravatar头像服务器的头像
		img_size= options[:size]
		# hash = Digest::MD5::hexdigest(user.email.downcase)
		# image_src = "http://www.gravatar.com/avatar/#{hash}?s=#{size}"
		#
		# image_tag image_src

		# 2根据图片在七牛的hash显示图片
		# @image=user.
		classname=case img_size
			          when '100' then 'avatar'
			          when '50' then 'small_avatar'
								when '60' then  'little_avatar'
			          else 'big_pic'
		          end



		defaultpic='ef61cdfec6a5d7fcc3603cb8d015b7a3aa.jpg'
		if user.avatar.present?
			image_tag(qiniu_image_by_hash(user.avatar),size: img_size,class: classname)
		else
			image_tag(qiniu_image_by_hash(defaultpic),size: img_size,class: classname)

		end

	end

	def generate_qiniu_upload_token
		key = 'abc.png'
		put_policy=Qiniu::Auth::PutPolicy.new("chenxiyue") #参数是七牛bucket名
		# put_policy.scope!("chenxiyue",key)
		put_policy.return_body={
			fname: '$(fname)',
			hash: '$(etag)',
			title:  '$(x:title)',
			newname: '$(key)'
		}.to_json
		put_policy.return_url= upload_callback_users_url  #上传成功后回调的URL
		Qiniu::Auth.generate_uptoken(put_policy)
	end

	def qiniu_image_url(img, format = :raw)
		url="http://7xsr0z.com2.z0.glb.qiniucdn.com/#{img.qiniu_hash}"    #为了方便硬编码七牛的域名

		case format
			when :square
				url << '?imageView2/1/w/300/h/300/q/90'
			when :preview
				url << '?imageView2/2/w/1000/h/1000/q/90'
			when :raw
				url << "?attname=#{img.filename}" #以原文件名进行下载
			else
				url
		end
	end

	def qiniu_image_by_hash(hash, format = :raw)
		url="http://7xsr0z.com2.z0.glb.clouddn.com/#{hash}"    #为了方便硬编码七牛的域名

		case format
			when :square
				url << '?imageView2/1/w/300/h/300/q/90'
			when :preview
				url << '?imageView2/2/w/1000/h/1000/q/90'
			else
				url
		end
	end

	# Override the filename of the uploaded files:
	def filename
		# if original_filename.present?
			# 1463728564-58814-0305
			@name = Digest::MD5.hexdigest(Time.now.utc.to_i.to_s + '-' + Process.pid.to_s + '-' + ("%04d" % rand(9999)))
			 # "#{@name}.#{file.extension}"
			"#{@name}"
		# end

	end



end
